//
//  BCMyProjectCell.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/26.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCMyProjectCell.h"

#import "BCProjectTagView.h"

#import "UserIndustryResponse.h"

//
#import "BCTimerHandler.h"
#import "NSDate+BCustom.h"

//顶部间隔距离
static CGFloat BCMyProjectCellTopPadding = 22.0;
//项目名称下方间隔
static CGFloat BCMyProjectNameBottomPadding = 20.0;
//
static CGFloat BCMyProjectDataPadding = 20.0;

static CGFloat BCMyProjectCellBottomPadding = 20.0f;
static CGFloat BCMyProjectCellAlertPadding = 12.0f;
static CGFloat BCMyProjectCellLeftRightPadding = 22.0f;

@interface BCMyProjectCell () <BCTimerHandlerDelegate>

/**
 *projectTextView
 */
@property (nonatomic, strong) YYTextView *projectTextView;

/**
 *BCProjectTagView
 */
@property (nonatomic, strong) BCProjectTagView *tagView;

/**
 *HomeCellDataView
 */
@property (nonatomic, strong) HomeCellDataView *totleDataView;

/**
 *HomeCellDataView
 */
@property (nonatomic, strong) HomeCellDataView *lastDataView;

/**
 *dataSpeLine
 */
@property (nonatomic, strong) UIView *dataSepLine;

/**
 *HomeCellDataView
 */
@property (nonatomic, strong) HomeCellDataView *joinDataView;
/**
 *gainDataView
 */
@property (nonatomic, strong) HomeCellDataView *gainDataView;


/**
 *alertLabel
 */
@property (nonatomic, strong) QMUILabel *alertLabel;


/**
 *BCTimerHandler 倒计时需要
 */
@property (nonatomic, strong) BCTimerHandler *timerHandler;

@end

@implementation BCMyProjectCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.fd_enforceFrameLayout = true;
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    self.projectTextView = [YYTextView new];
//    self.projectTextView.font = [UIFont systemFontOfSize:19 weight:UIFontWeightMedium];
//    self.projectTextView.textColor = [UIColor qmui_colorWithHexString:@"#666666"];
    self.projectTextView.userInteractionEnabled = false;
    self.projectTextView.textContainerInset = UIEdgeInsetsZero;
    [self.contentView addSubview:self.projectTextView];
    [self.projectTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView).offset(BCMyProjectCellLeftRightPadding);
        make.top.mas_equalTo(self.contentView).offset(BCMyProjectCellTopPadding);
        make.right.mas_equalTo(self.contentView).offset(-BCMyProjectCellLeftRightPadding);
        make.height.mas_greaterThanOrEqualTo(self.projectTextView.font.lineHeight);
    }];
    //
    self.tagView = [BCProjectTagView new];
    //
    self.totleDataView = [HomeCellDataView new];
    [self.contentView addSubview:self.totleDataView];
    [self.totleDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.projectTextView.mas_bottom).offset(20.0);
        make.left.mas_equalTo(self).offset(BCMyProjectCellLeftRightPadding);
        make.right.mas_equalTo(self.mas_centerX).offset(-BCMyProjectCellLeftRightPadding/2);
        make.height.mas_equalTo([HomeCellDataView defaultHeight]);
    }];
    self.lastDataView = [HomeCellDataView new];
    [self.contentView addSubview:self.lastDataView];
    [self.lastDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.totleDataView);
        make.left.mas_equalTo(self.mas_centerX).offset(BCMyProjectCellLeftRightPadding/2);
        make.right.mas_equalTo(self).offset(-BCMyProjectCellLeftRightPadding);
        make.height.mas_equalTo([HomeCellDataView defaultHeight]);
    }];
    //
    self.joinDataView = [HomeCellDataView new];
    [self.contentView addSubview:self.joinDataView];
    [self.joinDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.totleDataView.mas_bottom).offset(BCMyProjectDataPadding);
        make.left.mas_equalTo(self.totleDataView);
        make.right.mas_equalTo(self.totleDataView);
        make.height.mas_equalTo([HomeCellDataView defaultHeight]);
    }];
    //
    self.gainDataView = [HomeCellDataView new];
    [self.contentView addSubview:self.gainDataView];
    [self.gainDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.joinDataView);
        make.left.mas_equalTo(self.lastDataView);
        make.right.mas_equalTo(self.lastDataView);
        make.height.mas_equalTo(self.joinDataView);
    }];
    self.joinDataView.dataLabel.textColor = self.gainDataView.dataLabel.textColor = [UIColor darkMainColor];
    
    //
    self.dataSepLine = [UIView new];
    self.dataSepLine.backgroundColor = [UIColor separatorColor];
    [self.contentView addSubview:self.dataSepLine];
    [self.dataSepLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.totleDataView.mas_bottom).offset(BCMyProjectDataPadding/2);
        make.left.mas_equalTo(self.totleDataView);
        make.right.mas_equalTo(self.lastDataView);
        make.height.mas_equalTo(1.0);
    }];
    
    //
    UIEdgeInsets alertInsets = UIEdgeInsetsMake(4, 22, 4, 2);
    self.alertLabel = [QMUILabel new];
    self.alertLabel.textColor = [UIColor darkMainColor];
    self.alertLabel.backgroundColor = [[UIColor darkMainColor] colorWithAlphaComponent:0.1];
    self.alertLabel.contentEdgeInsets = alertInsets;
    self.alertLabel.numberOfLines = 0;
    self.alertLabel.font = [UIFont systemFontOfSize:11 weight:UIFontWeightRegular];
    [self.contentView addSubview:self.alertLabel];
    [self.alertLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.joinDataView.mas_bottom).offset(BCMyProjectCellAlertPadding);
        make.right.mas_equalTo(self.contentView).offset(-BCMyProjectCellLeftRightPadding);
        make.left.mas_equalTo(self.contentView).offset(BCMyProjectCellLeftRightPadding);
        make.height.mas_greaterThanOrEqualTo(self.alertLabel.font.lineHeight+alertInsets.top+alertInsets.bottom);
    }];
    //
    CGSize alertIVSize = CGSizeMake(12.0, 12.0);
    UIImageView *alertIV = [UIImageView new];
    alertIV.contentMode = UIViewContentModeScaleAspectFit;
    [self.alertLabel addSubview:alertIV];
    [alertIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.alertLabel).offset(alertInsets.left/2-alertIVSize.width/2);
        make.top.mas_equalTo(self.alertLabel.font.lineHeight/2+alertInsets.top-alertIVSize.height/2);
        make.size.mas_equalTo(alertIVSize);
    }];
    alertIV.image = LOAD_IMAGE(@"icon_countdown_h");
    //
    [self addSubview:self.separatorLine];
    self.separatorLine.backgroundColor = [UIColor separatorViewColor];
    [self addSubview:self.separatorLine];
    [self.separatorLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self);
        make.height.mas_equalTo(10.0);
    }];
}

- (CGSize)sizeThatFits:(CGSize)size {
    CGFloat height = 0;
    //顶部间隔距离
    height += BCMyProjectCellTopPadding;
    //项目名称高度
    CGFloat projectTextViewWidth = size.width-2*BCMyProjectCellLeftRightPadding;
    CGSize projectTextViewSize = [self.projectTextView sizeThatFits:CGSizeMake(projectTextViewWidth, CGFLOAT_MAX)];
    height += projectTextViewSize.height;
    //项目名称下方间隔距离
    height += BCMyProjectNameBottomPadding;
    //
    height += [HomeCellDataView defaultHeight];
    height += BCMyProjectDataPadding;
    height += [HomeCellDataView defaultHeight];
    //
    height += BCMyProjectCellAlertPadding;
    CGFloat alertWidth = size.width-2*BCMyProjectCellLeftRightPadding;
    CGFloat alertHeight = [self.alertLabel sizeThatFits:CGSizeMake(alertWidth, CGFLOAT_MAX)].height;
    height += alertHeight;
    //
    height += BCMyProjectCellBottomPadding;
    height += 10.0;
    [self.contentView layoutIfNeeded];
    return CGSizeMake(size.width, height);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGSize size = self.bounds.size;
    CGFloat projectTextViewWidth = size.width-2*BCMyProjectCellLeftRightPadding;
    CGSize projectTextViewSize = [self.projectTextView sizeThatFits:CGSizeMake(projectTextViewWidth, CGFLOAT_MAX)];
    [self.projectTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(projectTextViewSize.height);
    }];
}


- (void)setCellData:(UserIndustryDataModel *)cellData {
    _cellData = cellData;
    //
    if (cellData) {
        //设置项目名称 是否有预购标签
        [self setProjectTextViewContent:cellData];
        //
        self.totleDataView.title = [NSString stringWithFormat:@"%@(%@)",cellData.dataText.target,cellData.curr];
        self.totleDataView.data = cellData.amount;
        self.lastDataView.title = [NSString stringWithFormat:@"%@(%@)",cellData.dataText.surplus,cellData.curr];
        self.lastDataView.data = cellData.surplus;
        //
        self.joinDataView.title = [NSString stringWithFormat:@"%@(%@)",cellData.dataText.my_buy,cellData.curr];
        self.joinDataView.data = cellData.join_amount;
        self.gainDataView.title = [NSString stringWithFormat:@"%@(%@)",cellData.dataText.my_profit,cellData.curr];
        self.gainDataView.data = cellData.gain_amount;
        //
        [self setAlertLabelText:cellData];
        
        [self layoutSubviews];
    }
}
/**
 设置项目名称
 */
- (void)setProjectTextViewContent:(UserIndustryDataModel *)cellData {
    NSString *alertString;
    NSString *projectName = [cellData.project_name stringByAppendingFormat:@"(%@)",cellData.round];
    if (cellData.is_next) {//需要显示预购标签
        alertString = cellData.dataText.advance;
    }
    NSMutableAttributedString *projectAttributedText = [[NSMutableAttributedString alloc] init];
    //
    UIFont *font = [UIFont systemFontOfSize:19 weight:UIFontWeightMedium];
    if (alertString.length) {
        self.tagView.tintColor = [UIColor qmui_colorWithHexString:@"#3D5BFF"];
        self.tagView.alertTag = alertString;
        //
        CGSize size = CGSizeMake(CGRectGetWidth(self.tagView.frame)+15.0, CGRectGetHeight(self.tagView.frame));
        NSAttributedString *tagAttributedText = [NSAttributedString yy_attachmentStringWithContent:self.tagView contentMode:UIViewContentModeLeft attachmentSize:size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
        [projectAttributedText appendAttributedString:tagAttributedText];
    }
    NSAttributedString *projectNameAttriText = [[NSAttributedString alloc] initWithString:projectName attributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:[UIColor qmui_colorWithHexString:@"#666666"]}];
    [projectAttributedText appendAttributedString:projectNameAttriText];
    self.projectTextView.attributedText = projectAttributedText;
}
/**
 设置alertText
 */
- (void)setAlertLabelText:(UserIndustryDataModel *)cellData {
    //
    [self deallocTimerHandler];
    NSString *alertText = nil;
    switch (cellData.status) {
        case UserIndustryDataProjectStatus_0:
        {
            //您已预购成功，请等待开始
            alertText = cellData.dataText.status.s0;
        }
            break;
        case UserIndustryDataProjectStatus_1:
        {
            //倒计时 {}
            //                alertText = cellData.dataText.status.s1;
            alertText = [self fireCountdownStatus:cellData];
        }
            break;
        case UserIndustryDataProjectStatus_2:
        {
            //本轮筹集完成，预获利 {}，等待下一轮完成后发放本轮本金和利息
            alertText = cellData.dataText.status.s2;
            NSString *gainAmount = [NSString stringWithFormat:@"%@%@",cellData.gain_amount,cellData.curr];
            alertText = [alertText stringByReplacingOccurrencesOfString:@"{}" withString:gainAmount];
        }
            break;
        case UserIndustryDataProjectStatus_3:
        {
            //下一轮筹集完成，预获利 {}，等待结算和发放
            alertText = cellData.dataText.status.s3;
            NSString *gainAmount = [NSString stringWithFormat:@"%@%@",cellData.gain_amount,cellData.curr];
            alertText = [alertText stringByReplacingOccurrencesOfString:@"{}" withString:gainAmount];
        }
            break;
        case UserIndustryDataProjectStatus_4:
        {
            //下一轮筹集失败 本轮正在结算发放
            alertText = cellData.dataText.status.s4;
        }
            break;
        case UserIndustryDataProjectStatus_5:
        {
            //下一轮筹集完成,获利{},已经发放完成
            alertText = cellData.dataText.status.s5;
            NSString *gainAmount = [NSString stringWithFormat:@"%@%@",cellData.gain_amount,cellData.curr];
            alertText = [alertText stringByReplacingOccurrencesOfString:@"{}" withString:gainAmount];
        }
            break;
        case UserIndustryDataProjectStatus_6:
        {
            //下一轮筹集失败，本轮发放资金为投资本金的{}%
            alertText = cellData.dataText.status.s6;
            alertText = [alertText stringByReplacingOccurrencesOfString:@"{}" withString:cellData.them];
        }
            break;
        case UserIndustryDataProjectStatus_7:
        {
            //本轮募集失败，您的本金将全额无息退回
            alertText = cellData.dataText.status.s7;
        }
            break;
        default:
        {
            alertText = @"";
        }
            break;
    }
    self.alertLabel.text = alertText;
    [self.alertLabel sizeToFit];
}



//倒计时
- (NSString *)fireCountdownStatus:(UserIndustryDataModel *)cellData {
    _timerHandler = [[BCTimerHandler alloc] init];
    _timerHandler.delegate = self;
    [_timerHandler start];
    //
    return [self countDownString:cellData];
}


#pragma mark - BCTimerHandlerDelegate
- (void)timerHandlerRepeatsAction {
    if (self.cellData.status==UserIndustryDataProjectStatus_1) {
        self.alertLabel.text = [self countDownString:self.cellData];
    }
}
- (NSString *)countDownString:(UserIndustryDataModel *)cellData {
    NSDate *date = [BCServiceTimestampManager shared].date;
    NSDate *endDate = [NSDate stringToDate:cellData.end_time format:FullDateFormateString];
    //
    NSString *time = [NSDate countdownStringBetweenDate:date endDate:endDate];
    return [self.cellData.dataText.status.s1 stringByReplacingOccurrencesOfString:@"{}" withString:time];
}



- (void)deallocTimerHandler {
    if (_timerHandler) {
        [_timerHandler stop];
        _timerHandler.delegate = nil;
        _timerHandler = nil;
    }
}


- (void)dealloc {
    [self deallocTimerHandler];
}


@end
